use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use chrono::{DateTime, Utc};
use super::technical::{MarketAnalysis, MarketStateEnum};
use super::ml::MarketPrediction;
use std::clone::Clone;

/// 市场警报级别
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum AlertLevel {
    /// 信息
    Info,
    /// 警告
    Warning,
    /// 严重
    Critical,
    /// 紧急
    Emergency,
}

/// 市场警报类型
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum AlertType {
    /// 价格突破
    PriceBreakout,
    /// 趋势反转
    TrendReversal,
    /// 波动率异常
    VolatilityAnomaly,
    /// 成交量异常
    VolumeAnomaly,
    /// 技术指标信号
    TechnicalSignal,
    /// 模式识别
    PatternRecognition,
}

/// 市场警报
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MarketAlert {
    /// 警报ID
    pub id: String,
    /// 警报时间
    pub timestamp: DateTime<Utc>,
    /// 警报级别
    pub level: AlertLevel,
    /// 警报类型
    pub alert_type: AlertType,
    /// 警报消息
    pub message: String,
    /// 相关数据
    pub data: HashMap<String, f64>,
}

/// 市场状态快照
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MarketSnapshot {
    /// 快照时间
    pub timestamp: DateTime<Utc>,
    /// 当前价格
    pub price: f64,
    /// 成交量
    pub volume: f64,
    /// 市场分析结果
    pub analysis: MarketAnalysis,
    /// 市场预测
    pub prediction: Option<MarketPrediction>,
    /// 活跃警报
    pub active_alerts: Vec<MarketAlert>,
}

/// 回测结果
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BacktestResult {
    /// 开始时间
    pub start_time: DateTime<Utc>,
    /// 结束时间
    pub end_time: DateTime<Utc>,
    /// 初始资金
    pub initial_capital: f64,
    /// 最终资金
    pub final_capital: f64,
    /// 收益率
    pub return_rate: f64,
    /// 夏普比率
    pub sharpe_ratio: f64,
    /// 最大回撤
    pub max_drawdown: f64,
    /// 交易次数
    pub trade_count: usize,
    /// 胜率
    pub win_rate: f64,
    /// 详细交易记录
    pub trades: Vec<TradeRecord>,
}

/// 交易记录
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TradeRecord {
    /// 交易时间
    pub timestamp: DateTime<Utc>,
    /// 交易类型
    pub trade_type: TradeType,
    /// 交易价格
    pub price: f64,
    /// 交易数量
    pub quantity: f64,
    /// 交易金额
    pub amount: f64,
    /// 手续费
    pub fee: f64,
    /// 市场状态
    pub market_state: MarketStateEnum,
    /// 触发信号
    pub signal: String,
}

/// 交易类型
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum TradeType {
    /// 买入
    Buy,
    /// 卖出
    Sell,
}

/// 市场监控器
pub struct MarketMonitor {
    /// 警报配置
    alert_configs: Vec<AlertConfig>,
    /// 活跃警报
    active_alerts: Vec<MarketAlert>,
    /// 市场快照历史
    snapshots: Vec<MarketSnapshot>,
    /// 回测结果
    backtest_results: Option<BacktestResult>,
}

/// 警报配置
#[derive(Debug, Clone, Serialize, Deserialize)]
struct AlertConfig {
    /// 警报类型
    alert_type: AlertType,
    /// 警报级别
    level: AlertLevel,
    /// 触发条件
    conditions: HashMap<String, f64>,
}

impl MarketMonitor {
    /// 创建新的市场监控器
    pub fn new() -> Self {
        Self {
            alert_configs: Vec::new(),
            active_alerts: Vec::new(),
            snapshots: Vec::new(),
            backtest_results: None,
        }
    }

    /// 添加警报配置
    pub fn add_alert_config(&mut self, config: AlertConfig) {
        self.alert_configs.push(config);
    }

    /// 更新市场状态
    pub fn update(&mut self,
        timestamp: DateTime<Utc>,
        price: f64,
        volume: f64,
        analysis: MarketAnalysis,
        prediction: Option<MarketPrediction>,
    ) {
        // 检查警报条件
        self.check_alerts(price, volume, &analysis);

        // 创建新的市场快照
        let snapshot = MarketSnapshot {
            timestamp,
            price,
            volume,
            analysis,
            prediction,
            active_alerts: self.active_alerts.clone(),
        };

        // 保存快照
        self.snapshots.push(snapshot);

        // 清理过期数据
        self.cleanup_old_data();
    }

    /// 检查警报条件
    fn check_alerts(&mut self, price: f64, volume: f64, analysis: &MarketAnalysis) {
        // 清理过期警报
        let now = Utc::now();
        self.active_alerts.retain(|alert| {
            alert.timestamp + chrono::Duration::hours(24) > now
        });

        // 检查每个警报配置
        for config in &self.alert_configs {
            if self.should_trigger_alert(price, volume, analysis, config) {
                let alert = MarketAlert {
                    id: uuid::Uuid::new_v4().to_string(),
                    timestamp: Utc::now(),
                    level: config.level,
                    alert_type: config.alert_type.clone(),
                    message: self.generate_alert_message(config),
                    data: HashMap::new(),
                };
                self.active_alerts.push(alert);
            }
        }
    }

    /// 判断是否触发警报
    fn should_trigger_alert(&self, price: f64, volume: f64, analysis: &MarketAnalysis, config: &AlertConfig) -> bool {
        match config.alert_type {
            AlertType::PriceBreakout => {
                // 检查价格突破
                price > analysis.pivot_levels.resistance1
            },
            AlertType::VolumeAnomaly => {
                // 检查成交量异常
                volume > *config.conditions.get("volume_threshold").unwrap_or(&0.0)
            },
            _ => false,
        }
    }

    /// 生成警报消息
    fn generate_alert_message(&self, config: &AlertConfig) -> String {
        match config.alert_type {
            AlertType::PriceBreakout => "检测到价格突破".to_string(),
            AlertType::TrendReversal => "检测到趋势反转".to_string(),
            AlertType::VolatilityAnomaly => "检测到异常波动".to_string(),
            AlertType::VolumeAnomaly => "检测到异常成交量".to_string(),
            AlertType::TechnicalSignal => "检测到技术指标信号".to_string(),
            AlertType::PatternRecognition => "检测到市场模式".to_string(),
        }
    }

    /// 清理旧数据
    fn cleanup_old_data(&mut self) {
        // 保留最近7天的快照
        let cutoff = Utc::now() - chrono::Duration::days(7);
        self.snapshots.retain(|snapshot| snapshot.timestamp > cutoff);
    }

    /// 执行回测
    pub fn run_backtest(&mut self,
        start_time: DateTime<Utc>,
        end_time: DateTime<Utc>,
        initial_capital: f64,
    ) -> BacktestResult {
        let mut result = BacktestResult {
            start_time,
            end_time,
            initial_capital,
            final_capital: initial_capital,
            return_rate: 0.0,
            sharpe_ratio: 0.0,
            max_drawdown: 0.0,
            trade_count: 0,
            win_rate: 0.0,
            trades: Vec::new(),
        };

        // 过滤时间范围内的快照
        let test_snapshots: Vec<&MarketSnapshot> = self.snapshots.iter()
            .filter(|s| s.timestamp >= start_time && s.timestamp <= end_time)
            .collect();

        // 模拟交易
        let mut current_capital = initial_capital;
        let mut max_capital = initial_capital;
        let mut winning_trades = 0;

        for window in test_snapshots.windows(2) {
            let current = window[0];
            let next = window[1];

            // 根据市场状态和预测生成交易信号
            if let Some(trade) = self.generate_trade_signal(current, next) {
                result.trades.push(trade.clone());
                result.trade_count += 1;

                // 更新资金
                match trade.trade_type {
                    TradeType::Buy => {
                        current_capital -= trade.amount + trade.fee;
                    },
                    TradeType::Sell => {
                        current_capital += trade.amount - trade.fee;
                        if trade.amount > trade.quantity * current.price {
                            winning_trades += 1;
                        }
                    },
                }

                // 更新最大资金
                max_capital = max_capital.max(current_capital);
            }
        }

        // 计算回测指标
        result.final_capital = current_capital;
        result.return_rate = (current_capital - initial_capital) / initial_capital;
        result.max_drawdown = (max_capital - current_capital) / max_capital;
        result.win_rate = if result.trade_count > 0 {
            winning_trades as f64 / result.trade_count as f64
        } else {
            0.0
        };

        // 保存回测结果
        self.backtest_results = Some(result.clone());

        result
    }

    /// 生成交易信号
    fn generate_trade_signal(&self, current: &MarketSnapshot, next: &MarketSnapshot) -> Option<TradeRecord> {
        // 基于市场状态和预测生成交易信号
        if let Some(prediction) = &current.prediction {
            match prediction.predicted_state {
                MarketStateEnum::StrongBullish | MarketStateEnum::Bullish => {
                    Some(TradeRecord {
                        timestamp: next.timestamp,
                        trade_type: TradeType::Buy,
                        price: next.price,
                        quantity: 1.0,
                        amount: next.price,
                        fee: next.price * 0.001, // 0.1% 手续费
                        market_state: prediction.predicted_state.clone(),
                        signal: "看涨信号".to_string(),
                    })
                },
                MarketStateEnum::StrongBearish | MarketStateEnum::Bearish => {
                    Some(TradeRecord {
                        timestamp: next.timestamp,
                        trade_type: TradeType::Sell,
                        price: next.price,
                        quantity: 1.0,
                        amount: next.price,
                        fee: next.price * 0.001,
                        market_state: prediction.predicted_state.clone(),
                        signal: "看跌信号".to_string(),
                    })
                },
                _ => None,
            }
        } else {
            None
        }
    }
}